import {  tokenConfig, uploadFileApi_img , beforeFail } from "./config";
module.exports = {
    /* 
        file 必填 
            上传文件的 fileItem对象
        fileConfig 可选
            uni.uploadFile可选参数  success fail回调函数会被忽略
            默认上传接口为 上传图片
    */
    $uploadFile(file, fileConfig) {
        return new Promise((resolve, reject) => {
            if (file) {
                const defaultConfig = {
                    url:  uploadFileApi_img, //仅为示例，非真实的接口地址
                    filePath: file.path,
                    file: file.name,
                    name: 'file',
                    header: {
                        [tokenConfig.header_tokenKey]: tokenConfig.getUserInfo_token()
                    },
                };
                const finalConfig = Object.assign(defaultConfig, fileConfig, {
                    success(res) {
                        const { errMsg } = res;
                        if (errMsg === "uploadFile:ok") {
                            const resData = JSON.parse(res.data);
                            const { code } = resData;
                            let statusCode = Number(code);
                            resData.statusCode = statusCode;
                            function _next(data = resData, type = true) {
                                if (type) {
                                    resolve(data);
                                } else {
                                    reject(data);
                                }
                            }
                            //  status Error callback
                            if (beforeFail && typeof beforeFail === "function") {
                                const pagesArr = getCurrentPages();
                                const curPage = pagesArr[pagesArr.length - 1].$vm;
                                beforeFail(resData, { page: curPage, url: uploadFileApi_img }, _next);
                            } else {
                                // status success next
                                _next();
                            }
                        } else {
                            reject(`upLoad Error( errMsg ): [ ${url_notic} ] ${errMsg} `);
                        }

                    }
                    , fail(err) {
                        reject(err);
                    }
                });
                dd.uploadFile(finalConfig);
            } else {
                reject("missing necessary parameters: file");
            }

        });

    }
}